package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: RabbitService
 * Package: com.spzx.common.rabbit.service
 * Description:
 *
 * @Author ycy
 * @Create 2024/8/30 9:59
 * @Version 1.0
 */
@Service
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */
//    public boolean sendMessage(String exchange, String routingKey, Object message) {
//        rabbitTemplate.convertAndSend(exchange, routingKey, message);
//        return true;
//    }

    public boolean sendMessage(String exchange, String routingKey, Object message) {
        // 1.创建自定义相关消息对象-包含业务数据本身，交换机名称，路由键，队列类型，延迟时间，重试次数
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String uuid = "mq:" + UUID.randomUUID().toString().replace("-", "");
        correlationData.setId(uuid);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);

        // 2.将相关消息封装到发送消息的方法中
        // 这个方法的作用是将消息转换为指定的格式（例如 JSON、XML 等），然后将其发送到指定的交换机（Exchange）和队列（Queue）
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);

        // 3.将相关信息存入 Redis Key:UUID 相关消息对象 10 分钟
        // redisTemplate.opsForValue 用于获取一个操作 Redis 中值的操作对象
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);
        return true;
    }

    public boolean sendDelayMessage(String exchangeDelay, String routingDelay, Object message, int delayTime) {
        // 1.创建自定义相关消息对象-包含业务数据本身，交换器名称，路由键，队列类型，延迟时间，重试次数
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String uuid ="mq:" + UUID.randomUUID().toString().replaceAll("-","");
        correlationData.setId(uuid);
        correlationData.setExchange(exchangeDelay);
        correlationData.setRoutingKey(routingDelay);
        correlationData.setMessage(message);
        correlationData.setDelay(true);
        correlationData.setDelayTime(delayTime);

        // 2.将相关消息封装到发送消息方法中
        rabbitTemplate.convertAndSend(exchangeDelay,routingDelay,message,message1 -> {
            message1.getMessageProperties().setDelay(delayTime * 1000);
            return message1;
        },correlationData);
        return false;
    }
}
